﻿using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Goods.Entity;
using NewRetail.Application.Core;
using NewRetail.Application.Core.SingleStore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;

namespace NewRetail.Api.Controllers
{
    [NewRetailRoute("goods-category")]
    public class GoodsCategoryController : BaseController<GoodsCategory>
    {
        private readonly ISingleStoreService singleStoreService;
        public GoodsCategoryController(ISingleStoreService singleStoreService)
        {
            this.singleStoreService = singleStoreService;
        }

        protected override async Task<GoodsCategory> BeforeInsertDataInitial(GoodsCategory data)
        {
            if (string.IsNullOrWhiteSpace(data.No))
            {
                data.No = await this.NoGeneratorService.GenerateGoodsCategoryNoAsync(parentId: data.pID);
            }

            return await base.BeforeInsertDataInitial(data);
        }

        /// <summary>
        /// 商品分类中有商品时不能删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        protected override async Task<string[]> BeforeDelete(string[] ids)
        {
            string[] delIds=null;

            if (ids.Length > 0)
            {
                var db = await this.Repo.GetDbContextAsync();
                string[] categoryIDs = await db.Set<GoodsInfo>().AsNoTracking().Where(g => ids.Contains(g.categoryID)).Select(g => g.categoryID).Distinct().ToArrayAsync();
                //找出没有商品的分类
                delIds = ids.Where(id => !categoryIDs.Contains(id)).ToArray();
            }

            return delIds;
        }

        #region add by cl 20221111
        public override async Task<ResponseEntity<GoodsCategory[]>> QueryAll()
        {
            var data = await base.QueryAll();
            data.ThrowIfNotSuccess();
            data.Data ??= Array.Empty<GoodsCategory>();
            //单店权限
            string roleWarehouseId = this.singleStoreService.CurrentStore;
            data.Data = data.Data.WhereIf(!string.IsNullOrWhiteSpace(roleWarehouseId),
                x => x.warehouseID == roleWarehouseId)?.ToArray();

            data.Data = data.Data.OrderBy(x => x.No).ToArray();

            return data;
        }
        #endregion
    }
}
